<?php

/**
 * @descriptions: Generic file that contains functions that is used site wide
 */

/**
 * @description: out puts a formated variable. Usefull for debugging
 * @param mixed $var variable to print
 * @return void
 */
function pr($var) {
    echo '<pre>';
    print_r($var);
    echo '</pre>';
}

/**
 * @description: filter string.. remove unexpected input
 * @param string $str
 * @param bool $allowHtml if false remove html tags from input
 * @return string
 */
function filterVar($str, $allowHtml = true) {
    $notAllowed = array(
        'document.cookie' => '[removed]',
        'document.write' => '[removed]',
        '.parentNode' => '[removed]',
        '.innerHTML' => '[removed]',
        'window.location' => '[removed]',
        '-moz-binding' => '[removed]',
        '<!--' => '&lt;!--',
        '-->' => '--&gt;',
        '<![CDATA[' => '&lt;![CDATA[',
        '<comment>' => '&lt;comment&gt;',
        '<?' => '&lt;?',
        '?>' => '?&gt;',
    );

    $str = trim($str);

    $str = str_replace(array_keys($notAllowed), array_values($notAllowed), $str);

    $naughty = 'alert|applet|audio|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|isindex|layer|link|meta|object|plaintext|style|script|textarea|title|video|xml|xss';
    $str = preg_replace('#<(/*\s*)(' . $naughty . ')([^><]*)([><]*)#is', '[removed]', $str);

    $str = preg_replace('/<\?(php)/i', "&lt;?\\1", $str);

    if (!$allowHtml) {
        $str = strip_tags($str);
    }

    return $str;
}

/**
 * filter get and post variables
 */
function sanitizeInput() {
    if (!empty($_POST)) {
        foreach ($_POST as $key => $value) {
            $_POST[filterVar($key)] = filterVar($value);
        }
    }

    if (!empty($_GET)) {
        foreach ($_GET as $key => $value) {
            $_GET[filterVar($key)] = filterVar($value);
        }
    }
}

/**
 * url segments
 */
function getUrlSegments() {
    if (!isset($_SERVER['REQUEST_URI']) OR !isset($_SERVER['SCRIPT_NAME'])) {
        return array();
    }
    
    $uri = $_SERVER['REQUEST_URI'];
    
//    if (strpos($uri, $_SERVER['SCRIPT_NAME']) === false) {
//        $uri = substr($uri, strlen($_SERVER['SCRIPT_NAME']));
//    }
    
    $uri = str_replace($_SERVER['SCRIPT_NAME'], '', $uri);
    $uri = str_replace(array('//', '../'), '/', trim($uri, '/'));
    
    return explode('/', $uri);
}